# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/10/19 16:41
# File      : get_code.py
# explain   : 文件说明

import time
import os

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from common.config import local_config


class Base:
    code_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), local_config.code_path)

    def __init__(self, driver):
        self.driver = driver
        self.host = local_config.host

    def open_url(self, url):
        self.driver.get(url)

    def get_element(self, locator):
        try:
            # 使用匿名函数传入显示等待当中
            element = WebDriverWait(self.driver, 20, 0.5).until(
                lambda x: x.find_element(*locator))
        except Exception as e:
            raise
        return element

    def get_page_img(self, locator=None):
        """
        截图获取当前页面信息
        :return:
        """
        current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        current_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
        screenshot_path = os.path.join(current_path, local_config.screen_shot_path, f"{current_time}.png")

        if locator:
            print("执行这个")
            result = self.get_element(locator)
            result.screenshot(screenshot_path)
        else:
            print("这里应该不执行打印")
            self.driver.save_screenshot(screenshot_path)

    # def get_page_img(self, locator=None):
    #     """
    #     截图获取当前页面信息
    #     :return:
    #     """
    #     current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
    #     current_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    #     screenshot_path = os.path.join(current_path, local_config.screen_shot_path, f"{current_time}.png")
    #
    #     if locator:
    #         print("执行这个")
    #         result = self.driver.find_element(*locator)
    #         result.screenshot(screenshot_path)
    #
    #     else:
    #         print("这里应该不执行打印")
    #         self.driver.save_screenshot(screenshot_path)

    def quit(self):
        self.driver.quit()


if __name__ == '__main__':
    from common.browse import Browser

    driver = Browser().get_driver()
    bs = Base(driver)
    bs.open_url('https://shop.aircheng.com/simple/reg')
    time.sleep(2)
    # bs.get_page_img((By.XPATH, '//*[@id="captchaImg"]'))
    bs.get_page_img()
    time.sleep(2)
    bs.quit()
